package com.h3c.nem.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eos.common.constant.StatusCodeEnum;
import com.eos.common.custom.BusinessException;
import com.eos.common.util.CustomBeanUtils;
import com.eos.common.util.IdWorker;
import com.eos.common.util.UserUtils;
import com.h3c.nem.client.EosSyncDataClient;
import com.h3c.nem.dto.DeptManagerDTO;
import com.h3c.nem.dto.OptionsDTO;
import com.h3c.nem.dto.SdDeptDTO;
import com.h3c.nem.entity.*;
import com.h3c.nem.enums.AutoOpTypeEnum;
import com.h3c.nem.mapper.SdAllWorkerMapper;
import com.h3c.nem.mapper.SdDeptMapper;
import com.h3c.nem.mapper.SdEmailTemplateMapper;
import com.h3c.nem.mapper.SdUserMapper;
import com.h3c.nem.service.*;
import com.h3c.nem.utils.AppBusinessException;
import com.h3c.nem.utils.BusiEnumDefine;
import com.h3c.nem.utils.CommonUtil;
import com.h3c.nem.utils.InitExampleOrderByUtils;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Copyright (C), 2020-2020, h3c
 * FileName: SdDeptServiceImpl
 *
 * @Author: l22886
 * @Date: 2021-11-03
 * Description: sd_dept serviceImpl
 * Version: 1.0
 */
@Slf4j
@Service
public class SdDeptServiceImpl extends ServiceImpl<SdDeptMapper, SdDept> implements ISdDeptService {
    @Value("${block.bp.id}")
    private String blockBp;
    @Value("${block.dept.id}")
    private String blockDept;
    @Autowired
    private UserUtils userUtils;
    @Value("${performance.manage.account}")
    private String performanceAccount;
    @Value("${performance.manage.password}")
    private String performancePassword;

    @Value("${busi.adminids}")
    private String adminDomainAccounts;

    @Resource
    private SdDeptMapper sdDeptMapper;

    @Autowired
    private CommService commService;

    @Autowired
    private ISdAllWorkerService sdAllWorkerService;

    @Autowired
    private ISdUserService sdUserService;

    @Autowired
    private SdUserMapper sdUserMapper;

    @Autowired
    private EosSyncDataClient eosSyncDataClient;

    @Autowired
    private SdEmailTemplateMapper sdEmailTemplateMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    SdAllWorkerMapper sdAllWorkerMapper;

    @Autowired
    ITbWorkerService workerService;
    @Resource
    private ISdUserService iSdUserService;

    @Value("${inventory.account}")
    private String inventoryAccount;
    @Value("${inventory.password}")
    private String inventoryPassword;


    private static final String deptRedis = "nem_dept_";

    private static List<SdDept> allDeptCache = new ArrayList<>();

    /**
     * @title: selectFuzzyByDto
     * @description: 模糊查询操作
     * @params: [ dto ]
     * @return: java.util.List
     * @createTime: 2021-11-03
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public List<SdDeptDTO> selectFuzzyByDto(SdDeptDTO dto) {
        //List<SdDept> list = sdDeptMapper.selectByExample(initFuzzyExample(dto));
        List<SdDept> list = sdDeptMapper.queryListByFuzzy(JSONObject.parseObject(JSONObject.toJSONString(dto), SdDept.class));
        return JSONArray.parseArray(JSONArray.toJSONString(list), SdDeptDTO.class);
    }

    /**
     * @title: selectByDto
     * @description: 精确查询操作
     * @params: [ dto ]
     * @return: java.util.List
     * @createTime: 2021-11-03
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public List<SdDeptDTO> selectByDto(SdDeptDTO dto) {
        //List<SdDept> list = sdDeptMapper.selectByExample(initExample(dto));
        List<SdDept> list = sdDeptMapper.queryList(JSONObject.parseObject(JSONObject.toJSONString(dto), SdDept.class));
        return JSONArray.parseArray(JSONArray.toJSONString(list), SdDeptDTO.class);
    }

    /**
     * @title: insertDto
     * @description: 插入操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2021-11-03
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer insertDto(SdDeptDTO dto) {
        //if (null == dto.getId() || "".equals(dto.getId())) {
        //    String pkId = idWorker.nextId() + "";
        //    dto.setId(pkId);
        //}
        return sdDeptMapper.insertSdDept(JSONObject.parseObject(JSON.toJSONString(dto), SdDept.class));
    }

    /**
     * @title: updateDto
     * @description: 修改操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2021-11-03
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer updateDto(SdDeptDTO dto) {
        //if (null != dto && null != dto.getId() && !"".equals(dto.getId())) {
        return sdDeptMapper.updateSdDept(JSONObject.parseObject(JSON.toJSONString(dto), SdDept.class));
        //return sdDeptMapper.updateByPrimaryKey(JSONObject.parseObject(JSON.toJSONString(dto), SdDept.class));
        //} else {
        //    return 0;
        //}
    }

    /**
     * @title: deleteDto
     * @description: 删除操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2021-11-03
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer deleteDto(SdDeptDTO dto) {
        //if (null != dto && null != dto.getId() && !"".equals(dto.getId())) {
        return sdDeptMapper.deleteSdDept(JSONObject.parseObject(JSON.toJSONString(dto), SdDept.class));
        //return sdDeptMapper.deleteByPrimaryKey(dto.getId());
        //} else {
        //    return 0;
        //}
    }


    /**
     * @title: initFuzzyExample
     * @description: 初始化 模糊查询 example
     * @params: [ dto ]
     * @return: tk.mybatis.mapper.entity.Example
     * @createTime: 2021-11-03
     * @version: 1.0
     * @author: l22886
     */
    private Example initFuzzyExample(SdDeptDTO dto) {
        Example example = InitExampleOrderByUtils.initExampleOrderBy(SdDept.class, dto.getOrderBy());
        Example.Criteria criteriaName = example.createCriteria();
        if (null != dto) {
            if (null != dto.getDeptId() && !"".equals(dto.getDeptId())) {
                criteriaName.andLike("DeptId", "%" + dto.getDeptId() + "%");
            }
            if (null != dto.getDeptName() && !"".equals(dto.getDeptName())) {
                criteriaName.andLike("DeptName", "%" + dto.getDeptName() + "%");
            }
            if (null != dto.getDeptLevel() && !"".equals(dto.getDeptLevel())) {
                criteriaName.andLike("DeptLevel", "%" + dto.getDeptLevel() + "%");
            }
            if (null != dto.getParentId() && !"".equals(dto.getParentId())) {
                criteriaName.andLike("ParentId", "%" + dto.getParentId() + "%");
            }
            if (null != dto.getBpUserId() && !"".equals(dto.getBpUserId())) {
                criteriaName.andLike("BpUserId", "%" + dto.getBpUserId() + "%");
            }
            if (null != dto.getBpUserName() && !"".equals(dto.getBpUserName())) {
                criteriaName.andLike("BpUserName", "%" + dto.getBpUserName() + "%");
            }
            if (null != dto.getDeptStatus() && !"".equals(dto.getDeptStatus())) {
                criteriaName.andLike("DeptStatus", "%" + dto.getDeptStatus() + "%");
            }
            if (null != dto.getDeptNameChain() && !"".equals(dto.getDeptNameChain())) {
                criteriaName.andLike("DeptNameChain", "%" + dto.getDeptNameChain() + "%");
            }
            if (null != dto.getDeptCodeChain() && !"".equals(dto.getDeptCodeChain())) {
                criteriaName.andLike("DeptCodeChain", "%" + dto.getDeptCodeChain() + "%");
            }
            if (null != dto.getContactorId() && !"".equals(dto.getContactorId())) {
                criteriaName.andLike("ContactorId", "%" + dto.getContactorId() + "%");
            }
            if (null != dto.getContactorName() && !"".equals(dto.getContactorName())) {
                criteriaName.andLike("ContactorName", "%" + dto.getContactorName() + "%");
            }
            if (null != dto.getDeptManagerId() && !"".equals(dto.getDeptManagerId())) {
                criteriaName.andLike("DeptManagerId", "%" + dto.getDeptManagerId() + "%");
            }
            if (null != dto.getDeptManagerName() && !"".equals(dto.getDeptManagerName())) {
                criteriaName.andLike("DeptManagerName", "%" + dto.getDeptManagerName() + "%");
            }
            if (null != dto.getShortName() && !"".equals(dto.getShortName())) {
                criteriaName.andLike("ShortName", "%" + dto.getShortName() + "%");
            }
        }
        return example;
    }

    /**
     * @title: initExample
     * @description: 初始化 精确查询 example
     * @params: [ dto ]
     * @return: tk.mybatis.mapper.entity.Example
     * @createTime: 2021-11-03
     * @version: 1.0
     * @author: l22886
     */
    private Example initExample(SdDeptDTO dto) {
        Example example = InitExampleOrderByUtils.initExampleOrderBy(SdDept.class, dto.getOrderBy());
        Example.Criteria criteriaName = example.createCriteria();
        if (null != dto) {
            if (null != dto.getDeptId() && !"".equals(dto.getDeptId())) {
                criteriaName.andEqualTo("DeptId", dto.getDeptId());
            }
            if (null != dto.getDeptName() && !"".equals(dto.getDeptName())) {
                criteriaName.andEqualTo("DeptName", dto.getDeptName());
            }
            if (null != dto.getDeptLevel() && !"".equals(dto.getDeptLevel())) {
                criteriaName.andEqualTo("DeptLevel", dto.getDeptLevel());
            }
            if (null != dto.getParentId() && !"".equals(dto.getParentId())) {
                criteriaName.andEqualTo("ParentId", dto.getParentId());
            }
            if (null != dto.getBpUserId() && !"".equals(dto.getBpUserId())) {
                criteriaName.andEqualTo("BpUserId", dto.getBpUserId());
            }
            if (null != dto.getBpUserName() && !"".equals(dto.getBpUserName())) {
                criteriaName.andEqualTo("BpUserName", dto.getBpUserName());
            }
            if (null != dto.getDeptStatus() && !"".equals(dto.getDeptStatus())) {
                criteriaName.andEqualTo("DeptStatus", dto.getDeptStatus());
            }
            if (null != dto.getDeptNameChain() && !"".equals(dto.getDeptNameChain())) {
                criteriaName.andEqualTo("DeptNameChain", dto.getDeptNameChain());
            }
            if (null != dto.getDeptCodeChain() && !"".equals(dto.getDeptCodeChain())) {
                criteriaName.andEqualTo("DeptCodeChain", dto.getDeptCodeChain());
            }
            if (null != dto.getContactorId() && !"".equals(dto.getContactorId())) {
                criteriaName.andEqualTo("ContactorId", dto.getContactorId());
            }
            if (null != dto.getContactorName() && !"".equals(dto.getContactorName())) {
                criteriaName.andEqualTo("ContactorName", dto.getContactorName());
            }
            if (null != dto.getDeptManagerId() && !"".equals(dto.getDeptManagerId())) {
                criteriaName.andEqualTo("DeptManagerId", dto.getDeptManagerId());
            }
            if (null != dto.getDeptManagerName() && !"".equals(dto.getDeptManagerName())) {
                criteriaName.andEqualTo("DeptManagerName", dto.getDeptManagerName());
            }
            if (null != dto.getShortName() && !"".equals(dto.getShortName())) {
                criteriaName.andEqualTo("ShortName", dto.getShortName());
            }
        }
        return example;
    }


    /**
     * 更新本地部门缓存
     */
    private void updateAllDeptCache() {
        allDeptCache = sdDeptMapper.selectList(null);
    }


    private boolean chooseDept1(String dept1Id, List<String> deptIdList) {
        if (deptIdList.isEmpty()) {
            return true;
        }
        return deptIdList.contains(dept1Id);
    }


    private void doChildren(List<OptionsDTO> parent, Map<String, List<OptionsDTO>> children) {
        if (parent == null || parent.isEmpty()) {
            return;
        }
        parent.forEach(p -> {
            List<OptionsDTO> dtos = children.get(p.getValue());
            p.setChildren(dtos);
            doChildren(dtos, children);
        });
    }


    public Boolean userNotNullAndIsAdmin(String userId) {
        if (userId != null && !userId.equals("")) {
            SdUser sdUser = new SdUser();
            sdUser.setUserId(userId);
            SdUser sdUser1 = sdUserMapper.queryListByFuzzy(sdUser).get(0);
            for (String role : sdUser1.getUserRole().split(",")) {
                if (Integer.valueOf(role) == BusiEnumDefine.USER_ROLE_ADMIN){
                    return true;
                }
            }
            return false;
        } else {
            throw new BusinessException(StatusCodeEnum.UN_AUTH);
        }
    }

    @Override
    @Transactional
    @CacheEvict(value = "sdDeptList", key = "#p0", allEntries = true)
    public void synceSdDept(Boolean flag) {
        if (flag || userNotNullAndIsAdmin(commService.getLoginUserId())) {
            //未同步前的数据库中的部门信息
            List<SdDept> sdDeptListEx = sdDeptMapper.queryListByFuzzy(null);
            List<SdDept> sdDeptDOList = getSdDeptListFromEOS();

            //需要更新的部门
            List<SdDept> sdDeptUpdateList = new ArrayList<>();
            //需要插入的部门
            List<SdDept> sdDeptInsertList = new ArrayList<>();

            List<Integer> deptIdList = new ArrayList<>();
            sdDeptListEx.forEach(sdDept -> deptIdList.add(sdDept.getDeptId()));
            for (SdDept sdDept : sdDeptDOList) {
                String deptNameChain = sdDept.getDeptNameChain();
                if (deptNameChain.contains("新华三/研究开发部外协") ||
                        (deptNameChain.contains("新华三/中国区") && !deptNameChain.contains("中国区/智能终端产品线"))
                        || (deptNameChain.contains("新华三/项目部（虚拟）"))
                        || (deptNameChain.contains("新华三/项目部(虚拟)"))
                        || (deptNameChain.contains("新华三/新华三集团总部（暂设）"))
                        || (deptNameChain.contains("新华三/新华三集团总部(暂设)"))
//                        || (deptNameChain.contains("代表处服务部/项目交付部"))
//                        || blockDept.contains(sdDept.getDeptId().toString())
                ) {
                    continue;
                }
                if (deptIdList.contains(sdDept.getDeptId())) {
                    sdDeptUpdateList.add(sdDept);
                } else {
                    sdDeptInsertList.add(sdDept);
                }
            }
            if (!CollectionUtils.isEmpty(sdDeptUpdateList)) {
                for (SdDept sdDept : sdDeptUpdateList) {
                    sdDeptMapper.updateById(sdDept);
                }
            }
            if (!CollectionUtils.isEmpty(sdDeptInsertList)) {
                for (SdDept sdDept : sdDeptInsertList) {
                    sdDeptMapper.insert(sdDept);
                }
            }
            //同步主管信息
            syncDeptManager();
            commService.initDeptData();
            updateAllDeptCache();
        } else {
            throw new BusinessException(StatusCodeEnum.UN_AUTH);
        }
    }

    //部门配置人员离职邮件通知
    public void sendEmaiForDeptUserResign() {
        List<SdDept> sdDeptList = sdDeptMapper.selectList(new QueryWrapper<>());
        List<String> workerIdList = sdDeptList.stream().map(SdDept::getBpUserId).distinct().collect(Collectors.toList());
        List<String> contactorIdList = sdDeptList.stream().map(SdDept::getContactorId).distinct().collect(Collectors.toList());
        workerIdList.addAll(contactorIdList);
        List<String> gbbzIdList = sdDeptList.stream().map(SdDept::getGbbzId).distinct().collect(Collectors.toList());
        workerIdList.addAll(gbbzIdList);
        List<String> list = workerIdList.stream().distinct().collect(Collectors.toList());//部门表中配置的去重后的所有员工Id
        String ids = CommonUtil.contactListStrings(list);
        List<String> idList = Arrays.stream(ids.split(",")).distinct().collect(Collectors.toList());
        List<String> nullList = new ArrayList();
        nullList.add(null);
        nullList.add("null");
        nullList.add("");
        idList.removeAll(nullList);
        List<String> sendIdList = new ArrayList<>();
        log.info(sendIdList.toString());
//        Map<String, Object> dataCacheMap = CommService.dataCacheMap;
        List<SdAllWorker> sdAllWorkers = sdAllWorkerMapper.selectList(new QueryWrapper<>());
        List<String> sdWorkerIdList = sdAllWorkers.stream().map(SdAllWorker::getWorkerId).distinct().collect(Collectors.toList());
        for (String workerId : idList) {
//            if(!dataCacheMap.containsKey("allworker-"+workerId)){ //缓存莫名其妙失效
            if (!sdWorkerIdList.contains(workerId)) {
                sendIdList.add(workerId);
                log.info(workerId + "......................无相关人员........................");
            } else {
                log.info(workerId + "..............................相关人员存在...........................");
            }
        }
        if (sendIdList.size() > 0) {
            SdEmailTemplate taskEmail = sdEmailTemplateMapper.selectById(BusiEnumDefine.DEPR_RESIGN);
            String title = taskEmail.getEmailTemplateTitle();
            String content = taskEmail.getEmailTemplateContent();

            SdNoticeRecord sdNoticeRecord = new SdNoticeRecord();
            sdNoticeRecord.setNoticeId(IdWorker.nextId() + "");
            sdNoticeRecord.setFlowId("-1");
//            sdNoticeRecord.setApplyUserId(applyUserId);
            sdNoticeRecord.setNoticeType(BusiEnumDefine.NOTICE_TYPE_EMAIL);
            SdAllWorker manager = sdAllWorkerMapper.selectOne(new QueryWrapper<SdAllWorker>().eq("domain_account", adminDomainAccounts.split(",")[0]));
            sdNoticeRecord.setTargetId(manager.getWorkerId());
            sdNoticeRecord.setTargetName(manager.getWorkerName());
            sdNoticeRecord.setTargetEmail(manager.getEmail());
            sdNoticeRecord.setNoticeTitle(title);

            String sendIds = CommonUtil.contactListStrings(sendIdList);
            sdNoticeRecord.setNoticeContent(content.replace("{姓名/工号}", sendIds));
            log.info(sendIds);
            sdNoticeRecord.setCreateTime(new Date());
            commService.sendMessage(sdNoticeRecord);
        }
    }


    //获取一级部门Bp
    public  Map<Integer,String> getDept1BpMap(){
        List<SdDept> sdDeptLevel1List = sdDeptMapper.selectList(new QueryWrapper<SdDept>()
                .eq("dept_level",1)
                .isNotNull("bp_user_id"));
        List<SdDeptDTO> sdDeptDTOLevel1List = JSONArray.parseArray(JSONArray.toJSONString(sdDeptLevel1List),SdDeptDTO.class);
        Map<Integer,String> dept1BpMap = new HashMap<>();
        for (SdDeptDTO sdDeptDTO : sdDeptDTOLevel1List) {
            String firstBp = sdDeptDTO.getBpUserId();
            if(!StringUtils.isEmpty(firstBp)){
                String[] bpIds = firstBp.split(",");
                for (String bpId : bpIds) {
                    if (bpIds.length > 1 && !blockBp.contains(bpId)) {
                        firstBp = bpId;
                        break;
                    }else{
                        firstBp = "";
                    }
                }
                sdDeptDTO.setDept1BpOne(firstBp);
                dept1BpMap.put(sdDeptDTO.getDeptId(),firstBp);
            }else {
            }
        }
        return dept1BpMap;
    }

    //分部门给Bp发送邮件
    public void sendEmailForDeptUserNullForBp(List<SdDept> sdDeptList){
        Map<Integer,String> dept1BpMap = getDept1BpMap();
        List<SdDeptDTO> sdDeptDTOList = JSONArray.parseArray(JSONArray.toJSONString(sdDeptList),SdDeptDTO.class);
        Map<Integer,List<SdDeptDTO>> deptMap = new HashMap<>();
        if (sdDeptList.size() > 0) {
            for (SdDeptDTO sdDeptDTO : sdDeptDTOList) {
                sdDeptDTO.setDept1id(Integer.valueOf(sdDeptDTO.getDeptCodeChain().split("/")[1]));
            }
            deptMap = sdDeptDTOList.stream().collect(Collectors.groupingBy(SdDeptDTO::getDept1id));
        }
        for (Map.Entry<Integer, List<SdDeptDTO>> m : deptMap.entrySet()) {
            String bpId = dept1BpMap.get(m.getKey());
            if(!StringUtils.isEmpty(bpId)){
                List<SdDeptDTO> deptDTOS = m.getValue();
                SendEmailForBp(deptDTOS,bpId);
            }
        }
    }

    //部门人员为空维护邮件
    public void sendEmaiForDeptUserNull(List<SdDept> sdDeptList) {

        if (sdDeptList.size() > 0) {
            StringBuilder deptNameChains = new StringBuilder();
            for (SdDept sdDept : sdDeptList) {
                if(!sdDept.getDeptNameChain().endsWith("项目交付部")){
                    deptNameChains.append(sdDept.getDeptNameChain()).append("</br>");
                }
            }
            SdEmailTemplate taskEmail = sdEmailTemplateMapper.selectById(BusiEnumDefine.DEPT_USER_NULL);
            String title = taskEmail.getEmailTemplateTitle();
            String content = taskEmail.getEmailTemplateContent();

            SdNoticeRecord sdNoticeRecord = new SdNoticeRecord();
            sdNoticeRecord.setNoticeId(IdWorker.nextId() + "");
            sdNoticeRecord.setFlowId("-1");
//            sdNoticeRecord.setApplyUserId(applyUserId);
            sdNoticeRecord.setNoticeType(BusiEnumDefine.NOTICE_TYPE_EMAIL);
            SdAllWorker manager = sdAllWorkerMapper.selectOne(new QueryWrapper<SdAllWorker>().eq("domain_account", adminDomainAccounts.split(",")[0]));
            sdNoticeRecord.setTargetId(manager.getWorkerId());
            sdNoticeRecord.setTargetName(manager.getWorkerName());
            sdNoticeRecord.setTargetEmail(manager.getEmail());
            sdNoticeRecord.setNoticeTitle(title);
            sdNoticeRecord.setNoticeContent(content.replace("{部门}", deptNameChains.toString()));
            sdNoticeRecord.setCreateTime(new Date());
            commService.sendMessage(sdNoticeRecord);
        }
    }

    public void SendEmailForBp(List<SdDeptDTO> sdDeptList,String bpId ){
        if (sdDeptList.size() > 0) {
            StringBuilder deptNameChains = new StringBuilder();
            for (SdDeptDTO sdDept : sdDeptList) {
                deptNameChains.append(sdDept.getDeptNameChain()).append("</br>");
            }
            SdEmailTemplate taskEmail = sdEmailTemplateMapper.selectById(BusiEnumDefine.DEPT_USER_NULL);
            String title = taskEmail.getEmailTemplateTitle();
            String content = taskEmail.getEmailTemplateContent();

            SdNoticeRecord sdNoticeRecord = new SdNoticeRecord();
            sdNoticeRecord.setNoticeId(IdWorker.nextId() + "");
            sdNoticeRecord.setFlowId("-1");
//            sdNoticeRecord.setApplyUserId(applyUserId);
            sdNoticeRecord.setNoticeType(BusiEnumDefine.NOTICE_TYPE_EMAIL);
            SdAllWorker bp = commService.getAllWorkerDoFromLocalCache(bpId);
            sdNoticeRecord.setTargetId(bp.getWorkerId());
            sdNoticeRecord.setTargetName(bp.getWorkerName());
            sdNoticeRecord.setTargetEmail(bp.getEmail());
            sdNoticeRecord.setNoticeTitle(title);
            sdNoticeRecord.setNoticeContent(content.replace("{部门}", deptNameChains.toString()));
            log.info(sdNoticeRecord.getNoticeContent());
            sdNoticeRecord.setCreateTime(new Date());
            commService.sendMessage(sdNoticeRecord);
        }
    }
    /**
     * 部门人员维护邮件
     */
    @Override
    public void sendEmailForDept() {
        List<SdDept> sdDeptList = sdDeptMapper.selectList(new QueryWrapper<SdDept>().isNull("bp_user_id")
                .or().isNull("contactor_id")
                .or().isNull("gbbz_id"));
        sendEmaiForDeptUserNull(sdDeptList);
        //发送Bp
        sendEmailForDeptUserNullForBp(sdDeptList);
        sendEmaiForDeptUserResign();
    }

    private List<SdDept> getSdDeptListFromEOS() {
        try {
            String token = "Bearer " + commService.getEosDeptToken();
            JSONObject allDept = eosSyncDataClient.syncAllDept(token);
            List deptList = (List) allDept.get("data");
            List<SdDept> sdDeptList = new ArrayList<>();
            Map<String, String> needReplaceDeptNameMap = new HashMap<>();

            for (Object dept : deptList) {
                LinkedHashMap deptMap = (LinkedHashMap) dept;
                //SdDept sdDeptEx=sdDeptMapper.queryList(new SdDept().setDeptId(Integer.valueOf(((LinkedHashMap) dept).get("dept_code").toString()))).get(0);
                Integer deptId = Integer.valueOf(deptMap.get("dept_code").toString());
                SdDept sdDept = new SdDept();
                sdDept.setDeptId(deptId);
                if (!sdDeptMapper.queryList(sdDept).isEmpty()) {
                    SdDept sdDeptEx = sdDeptMapper.queryList(sdDept).get(0);
                    if (sdDeptEx != null) {
                        BeanUtils.copyProperties(sdDeptEx, sdDept);
                    }
                }
                //////////////////////////////////////测试环境数据有些名字为空，生产环境需要修改
                String deptName = deptMap.get("dept_name") == null ? deptMap.get("dept_code").toString() : deptMap.get("dept_name").toString();
                Integer deptLevel = Integer.valueOf(deptMap.get("dept_level").toString());
                //Integer deptCode = Integer.valueOf(((LinkedHashMap) dept).get("dept_code").toString());
                Integer supDeptCode = Integer.valueOf(deptMap.get("sup_dept_code").toString());
                String deptNameChain = deptMap.get("dept_name_chain").toString();
                String deptCodeChain = deptMap.get("dept_code_chain").toString();
                String deptType = deptMap.get("type_id") == null ? "" : deptMap.get("type_id").toString();
                String coaCode = deptMap.get("coa") == null ? "" : deptMap.get("coa").toString();

                if (!StringUtils.isEmpty(deptName)
                        && deptName.indexOf("/") > 0) {
                    String convertDetpName = deptName.replaceAll("/", "&");
                    needReplaceDeptNameMap.put(deptName, convertDetpName);
                    deptName = convertDetpName;
                }
                sdDept.setDeptName(deptName);
                //sdDept.setDeptId(deptCode);
                if (deptLevel == 1 && deptMap.get("deptAbbreviation") != null) {
                    sdDept.setShortName(deptMap.get("deptAbbreviation").toString());
                }
                sdDept.setDeptLevel(deptLevel);
                sdDept.setParentId(supDeptCode);
                sdDept.setDeptStatus(BusiEnumDefine.PD_DEPT_STATUS_NORMAL);
                sdDept.setDeptNameChain(deptMap.get("dept_name") == null ? deptNameChain + deptName : deptNameChain);
                sdDept.setDeptCodeChain(deptMap.get("dept_name") == null ? deptCodeChain + deptName : deptCodeChain);
                sdDept.setDeptType(deptType);
                sdDept.setCoaCode(coaCode);
                sdDeptList.add(sdDept);
            }
            for (SdDept sdDept : sdDeptList) {
                String deptNameChain = sdDept.getDeptNameChain();
                for (String needReplaceDeptName : needReplaceDeptNameMap.keySet()) {
                    if (!StringUtils.isEmpty(deptNameChain)
                            && deptNameChain.indexOf(needReplaceDeptName) > 0) {
                        deptNameChain = deptNameChain.replace(needReplaceDeptName, needReplaceDeptNameMap.get(needReplaceDeptName));
                        sdDept.setDeptNameChain(deptNameChain);
                    }
                }
            }
            return sdDeptList;
        } catch (Exception e) {
            throw e;
        }
    }

    //判断字符串是否数字开头
    public static boolean isStartWithNumber(String str) {
        Pattern pattern = Pattern.compile("[0-9].*");//一定记住加“.”
        Matcher isNum = pattern.matcher(str.charAt(0) + "");
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer setDeptUserRole(SdDeptDTO sdDeptDTO) {
        Map<String, Object> dataCacheMap = CommService.dataCacheMap;
        Integer deptId = sdDeptDTO.getDeptId();
        Integer userRole = sdDeptDTO.getUserRole();
        Integer personSetMode = sdDeptDTO.getPersonSetMode();
        Integer deptSetMode = sdDeptDTO.getDeptSetMode();
        String users = sdDeptDTO.getUsers();
        String[] usersArr = users.split(",");
//        List<SdAllWorker> sdAllWorkers = sdAllWorkerMapper.selectList(new QueryWrapper<SdAllWorker>().in("worker_id", usersArr));
        List<SdAllWorker> sdAllWorkers = new ArrayList<>();
        for (String s : usersArr) {
            SdAllWorker sdAllWorker = commService.getAllWorkerDoFromLocalCache(s);
            sdAllWorkers.add(sdAllWorker);
        }
        String userIdsNeed = "";
        StringBuilder tempUserIds = new StringBuilder();
        String userInfos = "";
        String tempUserInfos = "";
        for (SdAllWorker sdAllWorker : sdAllWorkers) {
            tempUserIds.append(",").append(sdAllWorker.getWorkerId());
//            tempUserIds.insert(0, sdAllWorker.getWorkerId() + ",");
//            userIdsNeed = tempUserIds.substring(0, tempUserIds.length() - 1);
            userIdsNeed = tempUserIds.substring(1, tempUserIds.length());
//            tempUserInfos = sdAllWorker.getWorkerName() + "/" + sdAllWorker.getWorkerId() + "," + tempUserInfos;
            tempUserInfos = tempUserInfos+","+sdAllWorker.getWorkerName() + "/" + sdAllWorker.getWorkerId();
            userInfos = tempUserInfos.substring(1, tempUserInfos.length());
        }
        String bpUserId = "";
        String bpUserName = "";
        String contactorId = "";
        String contactorName = "";
        String deptManagerId = "";
        String deptManagerName = "";
        String gbbzId = "";
        String gbbzName = "";
        String offerDeptManagerId= "";
        String offerDeptManagerName= "";
        //判断用户角色的
        if (userRole == 1) {
            bpUserId = userIdsNeed;
            bpUserName = userInfos;
        } else if (userRole == 2) {
            contactorId = userIdsNeed;
            contactorName = userInfos;
        } else if (userRole == 3) {
            deptManagerId = userIdsNeed;
            deptManagerName = userInfos;
        } else if (userRole == BusiEnumDefine.USER_ROLE_GBBZ) {
            gbbzId = userIdsNeed;
            gbbzName = userInfos;
        }else if (userRole == BusiEnumDefine.USER_ROLE_OFFER_DEPT_MANAGER) {
            offerDeptManagerId = userIdsNeed;
            offerDeptManagerName = userInfos;
        }
        //所有需要设置的部门
        List<SdDept> sdDeptListAll = new ArrayList<>();
        SdDept sdDept = new SdDept();
        sdDept.setDeptId(deptId);
        SdDept sdDeptSup = sdDeptMapper.queryList(sdDept).get(0);
        //只设置当前部门
        if (deptSetMode == 1) {
            sdDeptListAll.add(sdDeptSup);
        } else if (deptSetMode == 2) {
            SdDept sdDept1 = new SdDept();
            sdDept1.setDeptCodeChain(deptId.toString());
            sdDeptListAll = sdDeptMapper.queryListByFuzzy(sdDept1);
        }
        //循环处理所有需要设置的部门
        for (SdDept sdDeptNeedSet : sdDeptListAll) {
            //覆盖原有人员
            if (personSetMode == 1) {
                if (userRole == 1) {
                    //先删缓存
                    String exBpUserId = sdDeptNeedSet.getBpUserId();
                    if (exBpUserId != null) {
                        String[] exBpUserIdArr = exBpUserId.split(",");
                        for (String s : exBpUserIdArr) {
                            redisTemplate.delete("nem_dept_" + s);
                        }
                    }

                    sdDeptNeedSet.setBpUserId(bpUserId);
                    sdDeptNeedSet.setBpUserName(bpUserName);
                } else if (userRole == 2) {
                    //删缓存
                    String exContactorId = sdDeptNeedSet.getContactorId();
                    if (exContactorId != null) {
                        String[] exContactorIdArr = exContactorId.split(",");
                        for (String s : exContactorIdArr) {
                            redisTemplate.delete("nem_dept_" + s);
                        }
                    }
                    sdDeptNeedSet.setContactorId(contactorId);
                    sdDeptNeedSet.setContactorName(contactorName);
                } else if (userRole == 3) {
                  /*  if(deptManagerId.contains(",")){
                        throw new AppBusinessException("一级主管只允许设置一名人员！");
                    }else{
                        sdDeptNeedSet.setDeptManagerId(deptManagerId);
                        sdDeptNeedSet.setDeptManagerName(deptManagerName);
                    }*/
                    String exDeptManagerId = sdDeptNeedSet.getDeptManagerId();
                    if (exDeptManagerId != null) {
                        String[] exDeptManagerIdArr = exDeptManagerId.split(",");
                        for (String s : exDeptManagerIdArr) {
                            redisTemplate.delete("nem_dept_" + s);
                        }
                    }
                    sdDeptNeedSet.setDeptManagerId(deptManagerId);
                    sdDeptNeedSet.setDeptManagerName(deptManagerName);
                } else if (userRole == BusiEnumDefine.USER_ROLE_GBBZ) {
                    //删缓存
                    String exGbbzId = sdDeptNeedSet.getGbbzId();
                    if (exGbbzId != null) {
                        String[] exGbbzIdArr = exGbbzId.split(",");
                        for (String s : exGbbzIdArr) {
                            redisTemplate.delete("nem_dept_" + s);
                        }
                    }
                    sdDeptNeedSet.setGbbzId(gbbzId);
                    sdDeptNeedSet.setGbbzName(gbbzName);
                }else if (userRole == BusiEnumDefine.USER_ROLE_OFFER_DEPT_MANAGER) {
                    //删缓存
                    String exOfferDeptManagerId = sdDeptNeedSet.getOfferDeptManagerId();
                    if (exOfferDeptManagerId != null) {
                        String[] exOfferDeptManagerIdArr = exOfferDeptManagerId.split(",");
                        for (String s : exOfferDeptManagerIdArr) {
                            redisTemplate.delete("nem_dept_" + s);
                        }
                    }
                    sdDeptNeedSet.setOfferDeptManagerId(offerDeptManagerId);
                    sdDeptNeedSet.setOfferDeptManagerName(offerDeptManagerName);
                }
            } else if (personSetMode == 2) {//原有人员追加
                if (userRole == 1) {
                    if (sdDeptNeedSet.getBpUserId() != null && !Objects.equals(sdDeptNeedSet.getBpUserId(), "")) {
                        String bpUserIdAll = CommonUtil.moveSame(bpUserId + "," + sdDeptNeedSet.getBpUserId());
                        sdDeptNeedSet.setBpUserId(bpUserIdAll);
                        String bpUserNameAll = CommonUtil.moveSame(bpUserName + "," + sdDeptNeedSet.getBpUserName());
                        sdDeptNeedSet.setBpUserName(bpUserNameAll);
                    } else {
                        sdDeptNeedSet.setBpUserId(bpUserId);
                        sdDeptNeedSet.setBpUserName(bpUserName);
                    }
                } else if (userRole == 2) {
                    if (sdDeptNeedSet.getContactorId() != null && !Objects.equals(sdDeptNeedSet.getContactorId(), "")) {
                        String contactorIdAll = CommonUtil.moveSame(contactorId + "," + sdDeptNeedSet.getContactorId());
                        sdDeptNeedSet.setContactorId(contactorIdAll);
                        String contactorNameAll = CommonUtil.moveSame(contactorName + "," + sdDeptNeedSet.getContactorName());
                        sdDeptNeedSet.setContactorName(contactorNameAll);
                    } else {
                        sdDeptNeedSet.setContactorId(contactorId);
                        sdDeptNeedSet.setContactorName(contactorName);
                    }
                } else if (userRole == 3) {
                    if (sdDeptNeedSet.getDeptManagerId() != null && !Objects.equals(sdDeptNeedSet.getDeptManagerId(), "")) {
                        String deptManagerIdAll = CommonUtil.moveSame(deptManagerId + "," + sdDeptNeedSet.getDeptManagerId());
                        sdDeptNeedSet.setDeptManagerId(deptManagerIdAll);
                        String deptManagerNameAll = CommonUtil.moveSame(deptManagerName + "," + sdDeptNeedSet.getDeptManagerName());
                        sdDeptNeedSet.setDeptManagerName(deptManagerNameAll);
                    } else {
                        sdDeptNeedSet.setDeptManagerId(deptManagerId);
                        sdDeptNeedSet.setDeptManagerName(deptManagerName);
                    }
                } else if (userRole == BusiEnumDefine.USER_ROLE_GBBZ) {
                    if (sdDeptNeedSet.getGbbzId() != null && !Objects.equals(sdDeptNeedSet.getGbbzId(), "")) {
                        String gbbzIdAll = CommonUtil.moveSame(gbbzId + "," + sdDeptNeedSet.getGbbzId());
                        sdDeptNeedSet.setGbbzId(gbbzIdAll);
                        String gbbzNameAll = CommonUtil.moveSame(gbbzName + "," + sdDeptNeedSet.getGbbzName());
                        sdDeptNeedSet.setGbbzName(gbbzNameAll);
                    } else {
                        sdDeptNeedSet.setGbbzId(gbbzId);
                        sdDeptNeedSet.setGbbzName(gbbzName);
                    }
                } else if (userRole == BusiEnumDefine.USER_ROLE_OFFER_DEPT_MANAGER) {
                    if (sdDeptNeedSet.getOfferDeptManagerId() != null && !Objects.equals(sdDeptNeedSet.getOfferDeptManagerId(), "")) {
                        String offerDeptManagerIdAll = CommonUtil.moveSame(offerDeptManagerId + "," + sdDeptNeedSet.getOfferDeptManagerId());
                        sdDeptNeedSet.setOfferDeptManagerId(offerDeptManagerIdAll);
                        String offerDeptManagerNameAll = CommonUtil.moveSame(offerDeptManagerName + "," + sdDeptNeedSet.getOfferDeptManagerName());
                        sdDeptNeedSet.setOfferDeptManagerName(offerDeptManagerNameAll);
                    } else {
                        sdDeptNeedSet.setOfferDeptManagerId(offerDeptManagerId);
                        sdDeptNeedSet.setOfferDeptManagerName(offerDeptManagerName);
                    }
                }
            }
            //本地缓存
            dataCacheMap.put("dept-" + sdDeptNeedSet.getDeptId(), sdDeptNeedSet);
        }
        Integer num = 0;
        List<SdDeptDTO> sdDeptDTOList = JSONArray.parseArray(JSONArray.toJSONString(sdDeptListAll), SdDeptDTO.class);
        for (SdDeptDTO deptDTO : sdDeptDTOList) {

            if (sdDeptDTO.getUserRole() == 2) {
                deptDTO.setCityContactor(sdDeptDTO.getCityContactor());
            }
            deptDTO.setUserRole(sdDeptDTO.getUserRole());
            num = num + sdDeptMapper.updateSdDeptNem(deptDTO);
        }

        try {
            //需要覆盖人员上的接口人
            if (sdDeptDTO.getIsCoverOldWorkerDept() == 1) {
                Set<Integer> changeDeptIds = sdDeptDTOList.stream().map(SdDeptDTO::getDeptId).collect(Collectors.toSet());
                List<TbWorker> coverWorkerList = workerService.list(new QueryWrapper<TbWorker>().lambda()
                        .in(TbWorker::getDirectDeptId, changeDeptIds)
                        .in(TbWorker::getWorkerStatus, BusiEnumDefine.WORKER_STATUS_CONDUCT, BusiEnumDefine.WORKER_STATUS_WAIT));
                Map<Integer, SdDeptDTO> changeDeptMap = sdDeptDTOList.stream().collect(Collectors.toMap(SdDeptDTO::getDeptId, i -> i));
                for (TbWorker dbWorker : coverWorkerList) {
                    SdDeptDTO dept = changeDeptMap.get(dbWorker.getDirectDeptId());
                    String workCity = dbWorker.getWorkCity();
                    //城市接口人中存在
                    if (StringUtils.hasLength(dept.getCityContactor())
                            && StringUtils.hasLength(workCity)
                            && dept.getCityContactor().contains(workCity)) {
                        for (String s : dept.getCityContactor().split(";")) {
                            String[] city_con = s.split(":");
                            if (city_con[0].equals(workCity)) {
                                dbWorker.setDeptContactor(workerService.isChangeDeptCon(dbWorker, city_con[1]));
                                break;
                            }
                        }
                    } else {
                        dbWorker.setDeptContactor(workerService.isChangeDeptCon(dbWorker, dept.getContactorId()));
                    }
                }
                workerService.updateBatchById(coverWorkerList);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            throw new AppBusinessException("城市接口人格式错误");
        }
    /*    for (SdDept dept : sdDeptListAll) {
            num=num+ sdDeptMapper.updateSdDept(dept);
        }*/
        refreshDeptRedis();

        List<SdUser> sdUserList = sdUserMapper.queryList(new SdUser());
        List<String> userIdList = sdUserList.stream().map(SdUser::getUserId).collect(Collectors.toList());

        //同时加入用户表
        for (SdAllWorker sdAllWorker : sdAllWorkers) {
            if(!userIdList.contains(sdAllWorker.getWorkerId())){
                SdUser sdUser = new SdUser();
                sdUser.setUserId(sdAllWorker.getWorkerId());
                sdUser.setUserName(sdAllWorker.getWorkerName());
                sdUser.setDomainAccount(sdAllWorker.getDomainAccount());
                sdUser.setEmail(!StringUtils.isEmpty(sdAllWorker.getEmail())?sdAllWorker.getEmail():sdAllWorker.getDomainAccount()+"@h3c.com");
                if (userRole == 1) {
                    sdUser.setUserRole(String.valueOf(BusiEnumDefine.USER_ROLE_BP));
                } else if (userRole == 2) {
                    sdUser.setUserRole(String.valueOf(BusiEnumDefine.USER_ROLE_DEPT_CONTACTOR));
                } else if (userRole == BusiEnumDefine.USER_ROLE_GBBZ) {
                    sdUser.setUserRole(String.valueOf(BusiEnumDefine.USER_ROLE_GBBZ));
                }
                if(sdUser.getUserRole()!=null){
                    sdUserMapper.insert(sdUser);
                }
            }
        }
        //Integer n=sdDeptMapper.updateAll(sdDeptListAll);
        commService.recordAuthChangeLog("sd_dept", AutoOpTypeEnum.UPDATE, JSONObject.toJSONString(sdDeptDTO), "通过界面操作设置部门相关人员");
        return num;
    }

    @Override
    public Set<Integer> getDeptChildIds(String deptParentIds) {
        if (!StringUtils.isEmpty(deptParentIds)) {
            String[] deptIds = deptParentIds.split(",");
            List<SdDept> depts = new LinkedList<>();
            for (String deptId : deptIds) {
                depts.addAll(list(new QueryWrapper<SdDept>().like("dept_code_chain", deptId)));
            }
            return depts.stream().map(SdDept::getDeptId).collect(Collectors.toSet());
        }
        return null;
    }

    @Override
    public Set<Integer> getAuthDeptIds(boolean bpAuth, boolean conAuth, boolean manAuth, boolean gbbzAuth) {

        String loginUserId = commService.getLoginUserId();
        Set<Integer> authDeptIds = new HashSet<>();
        if (bpAuth || conAuth || gbbzAuth) {
            List<SdDept> authDeptList = list(new QueryWrapper<SdDept>()
                    .like(bpAuth, "bp_user_id", loginUserId).or()
                    .like(conAuth, "contactor_id", loginUserId).or()
                    .eq(gbbzAuth, "gbbz_id", loginUserId));
            authDeptIds.addAll(authDeptList.stream().map(SdDept::getDeptId).collect(Collectors.toSet()));
        }

        if (manAuth) {
            List<SdDept> managerDepts = list(new QueryWrapper<SdDept>().like("dept_manager_id", loginUserId));
            for (SdDept managerDept : managerDepts) {
                LambdaQueryWrapper<SdDept> qu = new QueryWrapper<SdDept>().lambda().like(SdDept::getDeptCodeChain, managerDept.getDeptId());
                List<SdDept> list = list(qu);
                Set<Integer> deptChildIds;
                if ((managerDept.getDeptLevel() == 1 || managerDept.getDeptLevel() == 2) && managerDept.getDeptNameChain().contains("集团代表处")) {
                    deptChildIds = list.stream().filter(i -> !(i.getDeptNameChain().contains("集团代表处") && i.getDeptNameChain().contains("服务部")))
                            .map(SdDept::getDeptId).collect(Collectors.toSet());
                } else {
                    deptChildIds = list.stream().map(SdDept::getDeptId).collect(Collectors.toSet());
                }
                authDeptIds.addAll(deptChildIds);
            }
        }
        //如果没有一个有权限的部门 设置一个查不到的部门
        if (authDeptIds.isEmpty()) {
            authDeptIds.add(1);
        }
        return authDeptIds;
    }


    /**
     * @title: download
     * @description: 部门信息导出
     * @params:
     * @return: File
     * @createTime: 2021-11-23
     * @version: 1.0
     * @author: j26296
     */
    @Override
    public File download(SdDeptDTO paramsDTO, String templateCode, String fileName) {
        SdDept sdDept = new SdDept();
        CustomBeanUtils.copyProperties(paramsDTO, sdDept);
        List<SdDept> sdDeptList = sdDeptMapper.queryListByFuzzy(sdDept);
        List<SdDeptDTO> sdDeptDTOS = constructDeptDTOList(sdDeptList);
        return commService.generateExportFile(fileName, templateCode, (List) sdDeptDTOS);
    }


    /**
     * @title: import
     * @description: 部门信息导入
     * @params:
     * @return: File
     * @createTime: 2021-11-23
     * @version: 1.0
     * @author: j26296
     */
    @Override
    public Integer importDeptSetList(MultipartFile file) {
        Map<String, Object> dataCacheMap = CommService.dataCacheMap;
        String fileContent = commService.parseExcelByTemplate("IMPORT_DEPT_LIST", file);
        JSONArray jsonArray = JSONArray.parseArray(fileContent);
        List<SdDeptDTO> sdDeptDTOSHave = selectFuzzyByDto(new SdDeptDTO());//数据库现存部门
        List<Integer> DeptIdList = new ArrayList<>();
        sdDeptDTOSHave.forEach(sdDeptDTO -> DeptIdList.add(sdDeptDTO.getDeptId()));
        List<SdDeptDTO> sdDeptDTOS = new ArrayList<>();
        for (Object jsonObj : jsonArray) {
            JSONObject jsonObject = JSONObject.parseObject(jsonObj.toString());
            SdDeptDTO sdDeptDTO = JSONObject.parseObject(jsonObject.toJSONString(), SdDeptDTO.class);
     /*       SdDeptDTO sdDeptDTO=new SdDeptDTO();
            String deptId=jsonObject.get("deptId").toString();
            sdDeptDTO.setDeptId(Integer.parseInt(jsonObject.get("deptId").toString()));
            sdDeptDTO.setDeptName(jsonObject.get("deptName").toString());*/
            //bp
            String bpUserId = jsonObject.get("bpUserId").toString();
            if (!StringUtils.isEmpty(bpUserId) && !bpUserId.equals("无")) {
                String[] bpUserIdArr = bpUserId.split(",");
//                List<SdAllWorker> sdAllWorkers = sdAllWorkerMapper.selectList(new QueryWrapper<SdAllWorker>().in("worker_id", bpUserIdArr));
                List<SdAllWorker> sdAllWorkers = new ArrayList<>();
                for (String s : bpUserIdArr) {
                    SdAllWorker sdAllWorker = commService.getAllWorkerDoFromLocalCache(s);
                    if(!ObjectUtils.isEmpty(sdAllWorker)) {
                        sdAllWorkers.add(sdAllWorker);
                    }
                }
                String userIdsNeed = "";
                StringBuilder tempUserIds = new StringBuilder();
                String userInfos = "";
                String tempUserInfos = "";
                for (SdAllWorker sdAllWorker : sdAllWorkers) {
                    tempUserIds.append(",").append(sdAllWorker.getWorkerId());
//            tempUserIds.insert(0, sdAllWorker.getWorkerId() + ",");
                    userIdsNeed = tempUserIds.substring(1, tempUserIds.length());
//            tempUserInfos = sdAllWorker.getWorkerName() + "/" + sdAllWorker.getWorkerId() + "," + tempUserInfos;
                    tempUserInfos = tempUserInfos+","+sdAllWorker.getWorkerName() + "/" + sdAllWorker.getWorkerId();
                    userInfos = tempUserInfos.substring(1, tempUserInfos.length());
                }
                sdDeptDTO.setBpUserId(userIdsNeed);
                sdDeptDTO.setBpUserName(userInfos);
            } else if (bpUserId.equals("无")) {
                sdDeptDTO.setBpUserId("");
                sdDeptDTO.setBpUserName("");
            } else if (bpUserId.equals("")) {
                sdDeptDTO.setBpUserId(null);
                sdDeptDTO.setBpUserName(null);
            }
            //contactor
            String contactorId = jsonObject.get("contactorId").toString();
            if (!StringUtils.isEmpty(contactorId) && !contactorId.equals("无")) {
                String[] contactorIdArr = contactorId.split(",");
                //List<SdAllWorker> sdAllWorkers= sdAllWorkerService.list(new QueryWrapper<SdAllWorker>().in("worker_id",contactorIdArr));
//                List<SdAllWorker> sdAllWorkers = sdAllWorkerMapper.selectList(new QueryWrapper<SdAllWorker>().in("worker_id", contactorIdArr));

                List<SdAllWorker> sdAllWorkers = new ArrayList<>();
                for (String s : contactorIdArr) {
                    SdAllWorker sdAllWorker = commService.getAllWorkerDoFromLocalCache(s);
                    if(!ObjectUtils.isEmpty(sdAllWorker)) {
                        sdAllWorkers.add(sdAllWorker);
                    }
                }
                String userIdsNeed = "";
                StringBuilder tempUserIds = new StringBuilder();
                String userInfos = "";
                String tempUserInfos = "";
                for (SdAllWorker sdAllWorker : sdAllWorkers) {
                    tempUserIds.append(",").append(sdAllWorker.getWorkerId());
//            tempUserIds.insert(0, sdAllWorker.getWorkerId() + ",");
                    userIdsNeed = tempUserIds.substring(1, tempUserIds.length());
//            tempUserInfos = sdAllWorker.getWorkerName() + "/" + sdAllWorker.getWorkerId() + "," + tempUserInfos;
                    tempUserInfos = tempUserInfos+","+sdAllWorker.getWorkerName() + "/" + sdAllWorker.getWorkerId();
                    userInfos = tempUserInfos.substring(1, tempUserInfos.length());
                }
                sdDeptDTO.setContactorId(userIdsNeed);
                sdDeptDTO.setContactorName(userInfos);
            } else if (contactorId.equals("无")) {
                sdDeptDTO.setContactorId("");
                sdDeptDTO.setContactorName("");
            } else if (contactorId.equals("")) {
                sdDeptDTO.setContactorId(null);
                sdDeptDTO.setContactorName(null);
            }
            //deptManager
            String deptManagerId = jsonObject.get("deptManagerId").toString();
            if (!StringUtils.isEmpty(deptManagerId) && !deptManagerId.equals("无")) {
                String[] deptManagerIdArr = deptManagerId.split(",");
                //List<SdAllWorker> sdAllWorkerss= sdAllWorkerService.list(new QueryWrapper<SdAllWorker>().in("worker_id",deptManagerIdArr));
//                List<SdAllWorker> sdAllWorkers = sdAllWorkerMapper.selectList(new QueryWrapper<SdAllWorker>().in("worker_id", deptManagerIdArr));

                List<SdAllWorker> sdAllWorkers = new ArrayList<>();
                for (String s : deptManagerIdArr) {
                    SdAllWorker sdAllWorker = commService.getAllWorkerDoFromLocalCache(s);
                    if(!ObjectUtils.isEmpty(sdAllWorker)){
                        sdAllWorkers.add(sdAllWorker);
                    }
                }
                String userIdsNeed = "";
                StringBuilder tempUserIds = new StringBuilder();
                String userInfos = "";
                String tempUserInfos = "";
                for (SdAllWorker sdAllWorker : sdAllWorkers) {
                    tempUserIds.append(",").append(sdAllWorker.getWorkerId());
//            tempUserIds.insert(0, sdAllWorker.getWorkerId() + ",");
                    userIdsNeed = tempUserIds.substring(1, tempUserIds.length());
//            tempUserInfos = sdAllWorker.getWorkerName() + "/" + sdAllWorker.getWorkerId() + "," + tempUserInfos;
                    tempUserInfos = tempUserInfos+","+sdAllWorker.getWorkerName() + "/" + sdAllWorker.getWorkerId();
                    userInfos = tempUserInfos.substring(1, tempUserInfos.length());
                }
                sdDeptDTO.setDeptManagerId(userIdsNeed);
                sdDeptDTO.setDeptManagerName(userInfos);
            } else if (deptManagerId.equals("无")) {
                sdDeptDTO.setDeptManagerId("");
                sdDeptDTO.setDeptManagerName("");
            } else if (deptManagerId.equals("")) {
                sdDeptDTO.setDeptManagerId(null);
                sdDeptDTO.setDeptManagerId(null);
            }
            //gbbz
            String gbbzId = jsonObject.get("gbbzId").toString();
            if (!StringUtils.isEmpty(gbbzId) && !gbbzId.equals("无")) {
                String[] gbbzIdArr = gbbzId.split(",");
//                List<SdAllWorker> sdAllWorkers = sdAllWorkerMapper.selectList(new QueryWrapper<SdAllWorker>().in("worker_id", gbbzIdArr));

                List<SdAllWorker> sdAllWorkers = new ArrayList<>();
                for (String s : gbbzIdArr) {
                    SdAllWorker sdAllWorker = commService.getAllWorkerDoFromLocalCache(s);
                    if(!ObjectUtils.isEmpty(sdAllWorker)) {
                        sdAllWorkers.add(sdAllWorker);
                    }

                }
                String userIdsNeed = "";
                StringBuilder tempUserIds = new StringBuilder();
                String userInfos = "";
                String tempUserInfos = "";
                for (SdAllWorker sdAllWorker : sdAllWorkers) {
                    tempUserIds.append(",").append(sdAllWorker.getWorkerId());
//            tempUserIds.insert(0, sdAllWorker.getWorkerId() + ",");
                    userIdsNeed = tempUserIds.substring(1, tempUserIds.length());
//            tempUserInfos = sdAllWorker.getWorkerName() + "/" + sdAllWorker.getWorkerId() + "," + tempUserInfos;
                    tempUserInfos = tempUserInfos+","+sdAllWorker.getWorkerName() + "/" + sdAllWorker.getWorkerId();
                    userInfos = tempUserInfos.substring(1, tempUserInfos.length());
                }
                sdDeptDTO.setGbbzId(userIdsNeed);
                sdDeptDTO.setGbbzName(userInfos);
            } else if (gbbzId.equals("无")) {
                sdDeptDTO.setGbbzId("");
                sdDeptDTO.setGbbzName("");
            } else if (gbbzId.equals("")) {
                sdDeptDTO.setGbbzId(null);
                sdDeptDTO.setGbbzName(null);
            }
            String cityContactor = jsonObject.get("cityContactor").toString();
            if (!StringUtils.isEmpty(cityContactor) && !cityContactor.equals("无")) {
                sdDeptDTO.setCityContactor(cityContactor);
            } else if (cityContactor.equals("无")) {
                sdDeptDTO.setCityContactor("");
            } else if (cityContactor.equals("")) {
                sdDeptDTO.setCityContactor(null);
            }
            sdDeptDTOS.add(sdDeptDTO);
        }
        List<SdDept> sdDeptList = JSONArray.parseArray(JSONArray.toJSONString(sdDeptDTOS), SdDept.class);
        Integer num = 0;
        for (SdDept sdDept : sdDeptList) {
            dataCacheMap.put("dept-" + sdDept.getDeptId(), sdDept);
            commService.recordAuthChangeLog("sd_dept", AutoOpTypeEnum.UPDATE, JSONObject.toJSONString(sdDept), "通过导入方法设置部门相关人员");
            num = num + sdDeptMapper.updateSdDept(sdDept);
        }
        try {
            //需要覆盖人员上的接口人

            Set<Integer> changeDeptIds = sdDeptList.stream().map(SdDept::getDeptId).collect(Collectors.toSet());
            List<TbWorker> coverWorkerList = workerService.list(new QueryWrapper<TbWorker>().lambda()
                    .in(TbWorker::getDirectDeptId, changeDeptIds)
                    .in(TbWorker::getWorkerStatus, BusiEnumDefine.WORKER_STATUS_CONDUCT, BusiEnumDefine.WORKER_STATUS_WAIT));
            Map<Integer, SdDept> changeDeptMap = sdDeptList.stream().collect(Collectors.toMap(SdDept::getDeptId, i -> i));
            for (TbWorker dbWorker : coverWorkerList) {
                SdDept dept = changeDeptMap.get(dbWorker.getDirectDeptId());
                String workCity = dbWorker.getWorkCity();
                //城市接口人中存在
                if (StringUtils.hasLength(dept.getCityContactor())
                        && StringUtils.hasLength(workCity)
                        && dept.getCityContactor().contains(workCity)) {
                    for (String s : dept.getCityContactor().split(";")) {
                        String[] city_con = s.split(":");
                        if (city_con[0].equals(workCity)) {
                            dbWorker.setDeptContactor(workerService.isChangeDeptCon(dbWorker, city_con[1]));
                            break;
                        }
                    }
                } else {
                    dbWorker.setDeptContactor(workerService.isChangeDeptCon(dbWorker, dept.getContactorId()));
                }
            }
            workerService.updateBatchById(coverWorkerList);

        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            throw new AppBusinessException("城市接口人格式错误");
        }
        //return sdDeptMapper.updateAll(sdDeptList);
        refreshDeptRedis();
        return num;
    }

    public List<SdDeptDTO> constructDeptDTOList(List<SdDept> sdDeptList) {
        List<SdDeptDTO> sdDeptDTOList = JSONArray.parseArray(JSONArray.toJSONString(sdDeptList), SdDeptDTO.class);
        for (SdDeptDTO sdDeptDTO : sdDeptDTOList) {
            String deptNameChain = sdDeptDTO.getDeptNameChain();
            String[] nameChains = deptNameChain.split("/");
            if (!StringUtils.isEmpty(sdDeptDTO.getDeptNameChain())) {
                Integer deptLevel = 0;
                for (String nameChin : nameChains) {
                    if (deptLevel == 1) {
                        sdDeptDTO.setDept1name(nameChin);
                    } else if (deptLevel == 2) {
                        sdDeptDTO.setDept2name(nameChin);
                    } else if (deptLevel == 3) {
                        sdDeptDTO.setDept3name(nameChin);
                    } else if (deptLevel == 4) {
                        sdDeptDTO.setDept4name(nameChin);
                    }
                    deptLevel++;
                }
            }
        }
        return sdDeptDTOList;
    }


    @Override
    public List<OptionsDTO> queryDeptTreeSelection(String deptIds) {
        List<String> deptIdList;
        if (StringUtils.isEmpty(deptIds)) {
            deptIdList = new ArrayList<>();
        } else {
            deptIdList = Arrays.asList(deptIds.split(","));
        }
        List<SdDept> sdDepts;
        if (allDeptCache.isEmpty()) {
            sdDepts = sdDeptMapper.selectList(null);
            allDeptCache = sdDepts;
        } else {
            sdDepts = allDeptCache;
        }
        List<OptionsDTO> optionList = new ArrayList<>();
        sdDepts.stream().filter(s -> !s.getDeptLevel().equals(0))
                .forEach(o -> optionList.add(new OptionsDTO(String.valueOf(o.getDeptId()),
                        o.getDeptName(), String.valueOf(o.getParentId()), getDeptNameChainNoH3c(o.getDeptNameChain()))));

        Map<String, List<OptionsDTO>> children = optionList.stream()
                .filter(o -> !"50040000".equals(o.getKey()))
                .collect(Collectors.groupingBy(OptionsDTO::getKey,
                        Collectors.collectingAndThen(Collectors.toList(), list -> list)));
        List<OptionsDTO> parent = optionList.stream().filter(o -> "50040000".equals(o.getKey()))
                .filter(o -> chooseDept1(o.getValue(), deptIdList)).collect(Collectors.toList());

        doChildren(parent, children);

        return parent;
    }

    /**
     * 获取没有新华三头部的nameChain
     * @param deptNameChain 部门表的nameChain
     * @return
     */
    public static String getDeptNameChainNoH3c(String deptNameChain) {
        if (deptNameChain.contains("/")) {
            int i = deptNameChain.indexOf("/");
            return deptNameChain.substring(i + 1);
        } else {
            return deptNameChain;
        }
    }

    //查询所有子部门
    @Override
    public List<SdDeptDTO> qyeryChidrenDeptList(SdDeptDTO sdDeptDTO) {

        SdDept sdDept = new SdDept();
        sdDept.setParentId(sdDeptDTO.getDeptId());
        List<SdDept> sdDeptList = sdDeptMapper.queryList(sdDept);
        List<SdDeptDTO> sdDeptDTOS = new ArrayList<>();
        for (SdDept dept : sdDeptList) {
            SdDeptDTO sdDeptDTO1 = new SdDeptDTO();
            BeanUtils.copyProperties(dept, sdDeptDTO1);
            SdDept sdDept1 = new SdDept();
            sdDept1.setParentId(dept.getDeptId());
            if (sdDeptMapper.queryList(sdDept1).size() > 0) {
                sdDeptDTO1.setHasChildren(true);
            } else {
                sdDeptDTO1.setHasChildren(false);
            }
            sdDeptDTOS.add(sdDeptDTO1);
        }

        //一级部门Bp开通权限
        boolean dept1Bp = commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_DEPT1BP);
        boolean admain = commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_ADMIN);
        if(dept1Bp&&!admain&&sdDeptDTO.getDeptId() == 50040000){
                List<SdDeptDTO> sdDeptDTOS1 = new ArrayList<>();
                for (SdDeptDTO deptDTO : sdDeptDTOS) {
                    if(!StringUtils.isEmpty(deptDTO.getBpUserId())&&deptDTO.getBpUserId().contains(commService.getLoginUserId())){
                        sdDeptDTOS1.add(deptDTO);
                    }
                }
                return sdDeptDTOS1;
        }
        return sdDeptDTOS;
    }

    //全量更新部门权限缓存
    public void refreshDeptRedis() {
//        commService.refreshDeptRedis();
    }

    //同步部门主管
    @Override
    public void syncDeptManager() {
        Map<String, Object> dataCacheMap = CommService.dataCacheMap;
        String token = userUtils.getToken(performanceAccount, performancePassword);
//        commService.getEosToken();
        // String token = userUtils.getToken(eosPrsAccount, eosPrsPassword);
        JSONObject allManager = eosSyncDataClient.queryDeptManage("Bearer " + token);
//        List<SdDept> newSddeptList = new ArrayList<>();
        List<SdDept> deptList = new ArrayList<>();
        JSONArray jsonArray = allManager.getJSONArray("data");
        List<DeptManagerDTO> deptManagerDTOS = JSONArray.parseArray(jsonArray.toJSONString(), DeptManagerDTO.class);
        Map<String, List<DeptManagerDTO>> map = deptManagerDTOS.stream().collect(
                Collectors.groupingBy(DeptManagerDTO::getDeptId));
        for (Map.Entry<String, List<DeptManagerDTO>> m : map.entrySet()) {
            SdDept sdDept = new SdDept();
            List<DeptManagerDTO> deptManagerDTOS1 = m.getValue();
            StringBuilder id = new StringBuilder();
            StringBuilder name = new StringBuilder();

            deptManagerDTOS1.forEach(deptManagerDTO1 -> {
                String newManagerId = deptManagerDTO1.getDeptManagerId();
                String newManagerName = deptManagerDTO1.getDeptManagerName();
                if (!StringUtils.isEmpty(newManagerId)) {
                    id.append(newManagerId).append(",");
                    name.append(newManagerName).append("/").append(newManagerId).append(",");
                    int l = id.length() - 1;
                    int n = name.length() - 1;
                    sdDept.setDeptManagerId(id.substring(0, l));
                    sdDept.setDeptManagerName(name.substring(0, n));
                }else {
                    sdDept.setDeptManagerId("");
                    sdDept.setDeptManagerName("");
                }
                sdDept.setDeptId(Integer.parseInt(m.getKey()));
            });
            deptList.add(sdDept);
        }
        deptList.forEach(dept -> {
            SdDept sdDept = (SdDept) dataCacheMap.get("dept-" + dept.getDeptId());
            if (!ObjectUtils.isEmpty(sdDept)) {
                XxlJobLogger.log(JSONObject.toJSONString(sdDept));
                sdDeptMapper.updateSdDeptManager(dept);
            }
        });


/*
        if(jsonArray!=null) {
            for (Object jsonObj : jsonArray) {
                JSONObject jsonObject = JSONObject.parseObject(jsonObj.toString());
                SdDept sdDept = (SdDept) dataCacheMap.get("dept-" + jsonObject.get("dept_code"));
                if (!ObjectUtils.isEmpty(sdDept)) {
                    String newManagerId = (String) jsonObject.get("emp_code");
                    String oldManagerId = sdDept.getDeptManagerId();
                    if (!StringUtils.isEmpty(newManagerId) && !newManagerId.equals(oldManagerId)) {
                        sdDept.setDeptManagerId(newManagerId);
                        sdDept.setDeptManagerName(jsonObject.get("emp_name") + "/" + newManagerId);
                        newSddeptList.add(sdDept);
                        sdDeptMapper.updateSdDept(sdDept);
                    }
                }
            }
        }*/
    }

    @Override
    public void modify() {
        List<SdDept> sdDepts1 = sdDeptMapper.selectList(new QueryWrapper<SdDept>()
//                .isNull("contactor_id").or().
                .eq("contactor_id", "")
                .isNotNull("contactor_name")
                .ne("contactor_name", ""));

        for (SdDept sdDept : sdDepts1) {
            String name = sdDept.getContactorName();
            String[] nameArr = name.split(",");
            StringBuilder sb = new StringBuilder();
            for (String s : nameArr) {
                String id = s.split("/")[1];
                sb.append(id).append(",");
            }
            String temp = sb.substring(0, sb.length() - 1);
            sdDept.setContactorId(temp);
            QueryWrapper queryWrapper1 = new QueryWrapper<SdDept>().eq("dept_id", sdDept.getDeptId());
            sdDeptMapper.update(sdDept, queryWrapper1);
        }

        List<SdDept> sdDepts2 = sdDeptMapper.selectList(new QueryWrapper<SdDept>()
//                .isNull("contactor_id").or().
                .eq("gbbz_id", "")
                .isNotNull("gbbz_name")
                .ne("gbbz_name", ""));

        for (SdDept sdDept : sdDepts2) {
            String name = sdDept.getGbbzName();
            String[] nameArr = name.split(",");
            StringBuilder sb = new StringBuilder();
            for (String s : nameArr) {
                String id = s.split("/")[1];
                sb.append(id).append(",");
            }
            String temp = sb.substring(0, sb.length() - 1);
            sdDept.setGbbzId(temp);
            QueryWrapper queryWrapper1 = new QueryWrapper<SdDept>().eq("dept_id", sdDept.getDeptId());
            sdDeptMapper.update(sdDept, queryWrapper1);
        }


        List<SdDept> sdDepts3 = sdDeptMapper.selectList(new QueryWrapper<SdDept>()
//                .isNull("contactor_id").or().
                .eq("bp_user_id", "")
                .isNotNull("bp_user_name")
                .ne("bp_user_name", ""));

        for (SdDept sdDept : sdDepts3) {
            String name = sdDept.getBpUserName();
            String[] nameArr = name.split(",");
            StringBuilder sb = new StringBuilder();
            for (String s : nameArr) {
                String id = s.split("/")[1];
                sb.append(id).append(",");
            }
            String temp = sb.substring(0, sb.length() - 1);
            sdDept.setBpUserId(temp);
            QueryWrapper queryWrapper1 = new QueryWrapper<SdDept>().eq("dept_id", sdDept.getDeptId());
            sdDeptMapper.update(sdDept, queryWrapper1);
        }


        List<SdDept> sdDepts4 = sdDeptMapper.selectList(new QueryWrapper<SdDept>()
//                .isNull("contactor_id").or().
                .eq("dept_manager_id", "")
                .isNotNull("dept_manager_name")
                .ne("dept_manager_name", ""));

        for (SdDept sdDept : sdDepts4) {
            String name = sdDept.getDeptManagerName();
            String[] nameArr = name.split(",");
            StringBuilder sb = new StringBuilder();
            for (String s : nameArr) {
                String id = s.split("/")[1];
                sb.append(id).append(",");
            }
            String temp = sb.substring(0, sb.length() - 1);
            sdDept.setDeptManagerId(temp);
            QueryWrapper queryWrapper1 = new QueryWrapper<SdDept>().eq("dept_id", sdDept.getDeptId());
            sdDeptMapper.update(sdDept, queryWrapper1);
        }

    }

    @Override
    public List<String> getBpManageDeptNameChainList(SFunction<SdDept, String> sFunction) {
        String loginUserId = commService.getLoginUserId();
        LambdaQueryWrapper<SdDept> queryWrapper = new QueryWrapper<SdDept>().lambda();
        queryWrapper.like(sFunction, loginUserId);
        List<SdDept> list = list(queryWrapper);
        return list.stream().map(SdDept::getDeptNameChain).map(o -> o.replace("新华三/", "")).collect(Collectors.toList());
    }

    @Override
    public SdDept getDeptByNameChain(String nameChain) {
        if (org.apache.commons.lang3.StringUtils.isBlank(nameChain)) {
            throw new AppBusinessException("参数异常：deptNameChain=" + nameChain);
        }
        LambdaQueryWrapper<SdDept> queryWrapper = new QueryWrapper<SdDept>().lambda();
        //集团代表处的都用新的
        queryWrapper.eq(SdDept::getDeptNameChain, "新华三/" + nameChain).orderByDesc(SdDept::getDeptId);
        List<SdDept> list = list(queryWrapper);
        if (list.isEmpty()) {
            throw new AppBusinessException("部门不存在：deptNameChain=" + nameChain);
        }
        return list.get(0);
    }

    @Override
    public SdDept getDeptByNameChainNoException(String nameChain) {
        if (!StringUtils.hasText(nameChain)) {
            return null;
        }
        LambdaQueryWrapper<SdDept> queryWrapper = new QueryWrapper<SdDept>().lambda();
        queryWrapper.eq(SdDept::getDeptNameChain, "新华三/" + nameChain).orderByDesc(SdDept::getDeptId);
        List<SdDept> list = list(queryWrapper);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    /**
     * 获取接口人
     *
     * @param deptNameChain
     * @param workCity
     * @return
     */
    @Override
    public String getContactorByDeptNameChain(String deptNameChain, String workCity) {
        SdDept dept = getDeptByNameChainNoException(deptNameChain);
        if (dept == null) {
            return "";
        }
        String contactors = "";
        String cityContactor = dept.getCityContactor();
        boolean getCon = false;
        if (!StringUtils.isEmpty(cityContactor)) {
            String[] cityContactors = cityContactor.split(";");
            for (String contactorId : cityContactors) {
                String[] city_ConId = contactorId.split(":");
                if (city_ConId[0].equals(workCity)) {
                    contactors = city_ConId[1];
                    getCon = true;
                    break;
                }
            }
        }
        if (!getCon && !StringUtils.isEmpty(dept.getContactorId())) {
            contactors = dept.getContactorId().split(",")[0];
        }
        return contactors;
    }

    /**
     * 获取负责入职期的BP
     *
     * @param deptNameChain
     * @param offerBpList   userRole是15的BP
     * @param bpList        userRole是14的BP
     * @return 返回 BpId
     */
    @Override
    public String getBpByDeptNameChain(String deptNameChain, List<String> offerBpList, List<String> bpList) {
        SdDept dept = getDeptByNameChainNoException(deptNameChain);
        StringBuilder bpSb = new StringBuilder();
        if (dept != null) {
            String bpUserId = dept.getBpUserId();
            if (StringUtils.hasText(bpUserId)) {
                for (String bpId : bpUserId.split(",")) {
                    if (offerBpList.contains(bpId)) {
                        bpSb.append(bpId).append(",");
                    } else if (bpList.contains(bpId)) {
                        bpSb.append(bpId).append(",");
                    }
                }
            }
        }
        return bpSb.toString();
    }

    /**
     * 获取负责入职期的BP
     *
     * @param deptNameChain
     * @return
     */
    @Override
    public String getBpByDeptNameChain(String deptNameChain) {
        List<SdUser> bpUser = sdUserMapper.selectList(new QueryWrapper<>());
        List<String> offerBpList = new ArrayList<>();
        List<String> bpList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(bpUser)) {
            bpUser.forEach(bp -> {
                for (String role : bp.getUserRole().split(",")) {
                    if(Integer.valueOf(role) == BusiEnumDefine.USER_ROLE_OFFER_BP){
                        offerBpList.add(bp.getUserId());
                    }
                    if (Integer.valueOf(role) == BusiEnumDefine.USER_ROLE_NEW_WORKER_BP){
                        bpList.add(bp.getUserId());
                    }
                }
            });
        }
        return getBpByDeptNameChain(deptNameChain, offerBpList, bpList);
    }

    @Override
    public Map<String, String> getWorkerMap(String workerIds) {
        log.info("获取{}员工信息", workerIds);
        List<SdAllWorker> bpWorkerList = Stream.of((workerIds).split(","))
                .map(id -> commService.getAllWorkerDoFromLocalCache(id)).filter(Objects::nonNull).collect(Collectors.toList());
        Map<String, String> result = new HashMap<>();
        String ids = bpWorkerList.stream().map(SdAllWorker::getWorkerId).collect(Collectors.joining(","));
        String names = bpWorkerList.stream().map(SdAllWorker::getWorkerName).collect(Collectors.joining(","));
        String emails = bpWorkerList.stream().map(SdAllWorker::getEmail).collect(Collectors.joining(","));
        result.put("ids", ids);
        result.put("names", names);
        result.put("emails", emails);
        log.info("返回员工信息：{}", result);
        return result;
    }

    @Override
    public List<String> getEmailList(String workerIds) {
        if (StringUtils.hasText(workerIds)) {
        List<SdAllWorker> bpWorkerList = Stream.of((workerIds).split(","))
                .map(id -> commService.getAllWorkerDoFromLocalCache(id)).collect(Collectors.toList());
        return bpWorkerList.stream().map(SdAllWorker::getEmail).collect(Collectors.toList());
        } else {
            return new ArrayList<>();
        }
    }

    @Override
    public Map<String, String> getBpAndContactorByDeptNameChain(String deptNameChain, String workCity) {
        String contactors = getContactorByDeptNameChain(deptNameChain, workCity);
        String bpUserId = getBpByDeptNameChain(deptNameChain);
        return getWorkerMap(contactors + "," + bpUserId);
    }

    @Override
    public String getSscDeptManagerId(String deptNameChain) {
        SdDept dept = getDeptByNameChainNoException(deptNameChain);
        if (dept == null) {
            return iSdUserService.getUserIdByRoleId(BusiEnumDefine.USER_ROLE_OFFER_SSC_MANAGER);
        }
        return dept.getOfferDeptManagerId();
    }

    @Override
    public Map<String, String> getBpAndContactorAndSSC(String deptNameChain, String workCity) {
        String contactors = getContactorByDeptNameChain(deptNameChain, workCity);
        String bpUserId = getBpByDeptNameChain(deptNameChain);
        String sscDeptManagerId = getSscDeptManagerId(deptNameChain);
        log.info("contactors={}, bpUserId={}, sscDeptManagerId={}", contactors, bpUserId, sscDeptManagerId);
        String emailTargetUser = Stream.of(contactors, bpUserId, sscDeptManagerId)
                .filter(org.apache.commons.lang3.StringUtils::isNotBlank).collect(Collectors.joining(","));
        if (StringUtils.isEmpty(emailTargetUser)) {
            return new HashMap<>();
        }
        return getWorkerMap(emailTargetUser);
    }

}
